package me.zhengjie.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import me.zhengjie.business.service.dto.BisQyRowDto;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lyl
 * @since 2023/11/3
 */
public class TreeBuilder {
    List<BisQyRowDto> nodes = new ArrayList<>();

    public JSONArray buildTree(List<BisQyRowDto> nodes) {
        TreeBuilder treeBuilder = new TreeBuilder(nodes);
        return treeBuilder.buildJSONTree();
    }

    public TreeBuilder() {
    }

    public TreeBuilder(List<BisQyRowDto> nodes) {
        super();
        this.nodes = nodes;
    }

    /**
     * 构建JSON树形结构
     */
    public JSONArray buildJSONTree() {
        List<BisQyRowDto> nodeTree = buildTree();
        String jsonStr = JSON.toJSONString(nodeTree, SerializerFeature.WriteNullStringAsEmpty);
        return JSONArray.parseArray(jsonStr);
    }

    /**
     * 构建树形结构
     */
    public List<BisQyRowDto> buildTree() {
        List<BisQyRowDto> treeNodes = new ArrayList<>();
        List<BisQyRowDto> rootNodes = getRootNodes();
        for (BisQyRowDto rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    /**
     * 递归子节点
     */
    public void buildChildNodes(BisQyRowDto node) {
        List<BisQyRowDto> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (BisQyRowDto child : children) {
                buildChildNodes(child);
            }
            node.setChildren(children);
        }
    }

    /**
     * 获取父节点下所有的子节点
     */
    public List<BisQyRowDto> getChildNodes(BisQyRowDto pnode) {
        List<BisQyRowDto> childNodes = new ArrayList<>();
        for (BisQyRowDto n : nodes) {
            if (pnode.getBisQyRowId().equals(n.getBisQyPid())) {
                childNodes.add(n);
            }
        }
        return childNodes;
    }

    /**
     * 判断是否为根节点
     */
    public boolean rootNode(BisQyRowDto node) {
        boolean isRootNode = true;
        for (BisQyRowDto n : nodes) {
            if (node.getBisQyPid().equals(n.getBisQyRowId())) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }

    /**
     * 获取集合中所有的根节点
     */
    public List<BisQyRowDto> getRootNodes() {
        List<BisQyRowDto> rootNodes = new ArrayList<>();
        for (BisQyRowDto n : nodes) {
            if (rootNode(n)) {
                rootNodes.add(n);
            }
        }
        return rootNodes;
    }
}
